<!--包含公司，部门的组织树-->
<template>
  <div>
    <a-tree-select
      v-model="currentValue"
      class="labelWrapper"
      v-bind="$attrs"
      v-on="$listeners"
      style="width: 100%"
      :tree-data="treeData"
      :treeExpandedKeys.sync="expandedKeys"
      :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
      :replaceFields="treeReplace"
      :tree-checkable="treeCheckable"
      :show-checked-strategy="showCheckedStrategy"
      @treeExpand="handleTreeExpand"
      @select="handleSelect"
      @change="handleChange"
      placeholder="请选择"
    />
  </div>
</template>
<script>
import Bus from '@/tool/Bus.js'
import { TreeSelect } from 'ant-design-vue'
import { getOrgsTree, getStaffAll, getCustOrgTree, getCustOrgTreeScreening } from '@/api/subassembly/TreeSelectOrganization'
const SHOW_ALL = TreeSelect.SHOW_ALL //显示所有选中节点(包括父节点).
const SHOW_PARENT = TreeSelect.SHOW_PARENT //只显示父节点(当父节点下所有子节点都选中时)
const SHOW_CHILD = TreeSelect.SHOW_CHILD //默认只显示子节点.

export default {
  name: 'TreeSelectOrganization',
  props: {
    /**
     * @description: 定义选中项回填的方式
     * @param {} SHOW_ALL  显示所有选中节点(包括父节点).
     * @param {} SHOW_PARENT  只显示父节点(当父节点下所有子节点都选中时)
     * @param {} SHOW_CHILD  默认只显示子节点
     */
    showCheckedStrategy: {
      default: SHOW_CHILD
    },
    treeCheckable: {
      // 是否有复选框
      type: Boolean,
      default: false
    },
    // 组织树查询参数，undefined时使用默认值否则需要补齐参数
    orgQuery: {
      type: Object,
      default: () => {}
    },
    //不联动（默认值）：onlyOrg;
    //联动工作：jobs
    //联动人员：staff
    childrenNode: {
      type: String,
      default: 'onlyOrg'
    },
    staff: {
      //是否请求人员列表
      type: Boolean,
      default: false
    },
    jobs: {
      //是否有职位
      type: Boolean,
      default: false
    },
    screening: {
      type: Boolean,
      default: false
    },
    // 是否包含虚拟组织结构
    containVirtual: {
      type: Boolean,
      default: false
    },
    // v-model绑定的数据
    value: {
      type: [Array, String, Object, Number]
    },
    // 是否禁用父级，只启用末级
    parentDisabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      SHOW_ALL,
      SHOW_PARENT,
      SHOW_CHILD,
      showSearch: true,
      treeData: [],
      treeReplace: {
        title: 'label',
        value: 'id',
        key: 'id'
      },
      orgSelected: {
        value: {},
        label: {}
      },
      expandedKeys: [] // 展开节点
    }
  },
  computed: {
    // 转换绑定的选中数据，与v-model同步
    currentValue: {
      get: function () {
        return this.value
      },
      set: function (value) {
        this.$emit('input', value)
      }
    },
    // 组织数据
    orgData() {
      return JSON.stringify(this.orgQuery || {}) !== '{}'
        ? this.orgQuery
        : {
            baseOrgType: 0, // 是否基础组织 0否 1是
            containVirtual: 0, //是否包含虚拟组织 0包含 1 不包含
            systemOrgType: 1 //公司组织默认1
            // orgDeptTagCodes: this.GET_ORGLABEL.map((el) => el.code) // 查询指定组织层级下部门，默认全量(不传就是全量)
            // orgDeptTagCode: "CO", // 查询指定组织层级下部门;与orgDeptTagCodes二选一
          }
    }
  },
  created() {
    // getOrgsTree({containVirtual:0}).then(res => {
    //   if(res.status === 200){
    //     this.treeData = res.data
    //     // this.treeData = this.parentTreeFun(res.data)
    //   }
    // })
    const _this = this
    if (this.screening) {
      getCustOrgTreeScreening({ ..._this.orgData, containVirtual: this.containVirtual ? 1 : 0 }).then((res) => {
        if (res.status === 200) {
          this.parentDisabled && this.fomatDatas(res.data)
          // 添加展开节点
          this.expandedKeys.push(res.data?.[0].id)
          this.treeData = res.data
          // this.treeData = this.parentTreeFun(res.data)
        }
      })
    } else {
      getCustOrgTree({ containVirtual: this.containVirtual ? 1 : 0, baseOrgType: 1 }).then((res) => {
        if (res.status === 200) {
          this.parentDisabled && this.fomatDatas(res.data)
          this.expandedKeys.push(res.data?.[0].id)
          this.treeData = res.data
          // this.treeData = this.parentTreeFun(res.data)
        }
      })
    }
  },
  methods: {
    /**
     * 转换多级数组为一级数组
     */
    fomatDatas(datas) {
      for (let index in datas) {
        let item = datas[index]
        if (item.children) {
          item.children.forEach((i) => {
            i.parentName = item[this.treeReplace.title]
            i.name = item[this.treeReplace.title] + '/' + i[this.treeReplace.title]
          })
          // 非末级都禁用
          item.disabled = true
          this.fomatDatas(item.children)
        }
      }
    },
    /**
     * @description: 展开节点时调用
     * @param {object} expandedKeys 展开节点时的对象
     */
    handleTreeExpand(expandedKeys) {
      this.$emit('update:expandedKeys', expandedKeys)
      this.$emit('handleExpandedKeys', expandedKeys)
    },
    /**
     * @description: 被选中时调用
     * @param {string} value 被选中时调用的id字符串
     */
    handleSelect(value, node, extra) {
      // console.log(this.orgSelected)
      this.$emit('update:orgSelectValue', value)
      this.$emit('handleSelect', value)
    },
    /**
     * @description: 选中树节点时调用此函数
     * @param {object} value  选中树节点的id
     * @param {object} label  选择树节点的文本信息对象
     */
    handleChange(value, label, extra) {
      // console.log('1' + this.orgSelected)
      this.orgSelected = {
        value: value,
        label: label,
        data: extra.triggerNode?.dataRef
      }
      // console.log('2' + this.orgSelected)
      this.$emit('update:orgSelectedValue', value)
      this.$emit('update:orgSelectedLabel', label)
      this.$emit('handleChange', extra.triggerNode?.dataRef)
      if (this.childrenNode === 'staff') {
        extra.haveJobs = false
        Bus.$emit('GetStaff', extra)
        this.tip(extra)
      } else if (this.childrenNode === 'jobs') {
        extra.haveJobs = true
        Bus.$emit('GetJobs', extra)
        this.tip(extra)
      }
    },
    /**
     * @description: 联动为单选提示
     */
    tip(extra) {
      if (extra.selected) {
      } else {
        // console.log('连动时请设置为单选')
      }
    }
    /**
     * @description: 返回数据整理成页面对于的对象树选择
     * @param {function} parentTreeFun  父节点遍历子节点
     * @param {function} childrenTreeFun  返回子节点对象，将子节点中children作为父节点继续遍历，以此循环重组所有的数据
     */
    // parentTreeFun(data){
    //   return data.map((value, key, arr)=>{
    //     return this.childrenTreeFun(value);
    //   });
    // },
    // childrenTreeFun(value){
    //   let obj = {
    //     title: value.label,
    //     value: value.label,
    //     key: value.id,
    //     pid: value.pid,
    //     data: value.data,
    //   }
    //   if (value.children) {
    //     obj.children = this.parentTreeFun(value.children);
    //   }
    //   return obj;
    // },
  },
  mounted() {}
}
</script>
<style scoped>
.ant-select-dropdown .ant-select-dropdown-content .ant-select-tree /deep/ .ant-select-tree-treenode-switcher-close {
  line-height: 12px;
}
</style>
